'use strict';

const Controller = require('egg').Controller;
const { toBase64 } = require('../../util')
// import { Controller } from 'egg'

class LoginController extends Controller {
  // 登录
  async index() {
    const { ctx, app } = this
    
    const { account = '', password = '', remember = '' } = ctx.request.body
    const ExsitedList = await app.model.AdminUser.findOne({
      where: {
        account, password
      }
    })
    
    if (ExsitedList && ExsitedList.id) {
      // 存在此用户
      // 记住用户
      const userInfo = {
          account: account,
          userId: ExsitedList.id,
          username: ExsitedList.username,
          wechat: ExsitedList.wechat || '',
          QQ: ExsitedList.qq || '',
          github:ExsitedList.github || '',
          keywords:ExsitedList.keywords,
          description:ExsitedList.description,
          sendword:ExsitedList.sendword,
      }
      if (remember) {
        const sessionId = `${account}_${new Date().getTime()}`
 
        ctx.session.userInfo = Object.assign({}, userInfo, {sessionId})
       
        // 更新该用户在表中的sessionId
        await app.model.AdminUser.update({session_id: sessionId}, {
          where: { 
            account: account
          }
        })
        ctx.body = { success: true, userInfo: toBase64(JSON.stringify(userInfo)), msg: '登录成功' }
      } else {
        ctx.body = { success: true, userInfo: toBase64(JSON.stringify(userInfo)), msg: '登录成功' }
      }

    } else {
      ctx.body = { success: false, msg: '登录失败', code: '账号或密码错误！' };
    }

  }
}

module.exports = LoginController;
